package top.malaoshi.webmvc.parameter;

import top.malaoshi.webmvc.info.MethodsArgumentInfo;
import top.malaoshi.webmvc.exception.RequestParamResolverException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 从request对象中取出参数，并放入 Map（或Map实现类） 的形参中
 * 如果形参是 Map，默认用 LinkedHashMap ，因为有顺序
 */
public class MapResolver extends AbstractResolver implements RequestParamAndMethodArgsResolver {
    @Override
    public Object resolver(HttpServletRequest request, HttpServletResponse response , MethodsArgumentInfo mai) throws RequestParamResolverException {
        checkNameAndValue(mai);
        //String parameterName = getName(mai);
        Enumeration<String> parameterNames = request.getParameterNames();
        Map<String, String[]> parameterMap = request.getParameterMap();
        Class type = mai.getType();
        Map ret = null;
        if(parameterMap!=null) {
            int len = parameterMap.size();
            if(type == Map.class || type == LinkedHashMap.class) {
                // 默认用 LinkedHashMap ，因为有顺序
                ret = new LinkedHashMap(len);
            }else{
                try {
                    ret = (Map)type.newInstance();
                } catch (InstantiationException e) {
                    throw new RequestParamResolverException(e);
                } catch (IllegalAccessException e) {
                    throw new RequestParamResolverException(e);
                }
            }
//            Class generic = (Class) mai.getType().getGenericSuperclass();
            if(len>0) {
                while(parameterNames.hasMoreElements()){
                    String name = parameterNames.nextElement();
                    String[] value = parameterMap.get(name);
                    ret.put(name,value);
                }
            }
        }
        checkRequired(ret,mai);
        return ret;
    }
}
